#include "stdafx.h"

#include<stdlib.h>
#include<stdio.h>
#include"Status.h"
#include"SqList.h"

Status InitList(SqList *L)
{
    L->base = (int *)malloc(INIT_SIZE*sizeof(int));
    
	if(!L->base)
	return ERROR;

    L->length = 0;
    L->listsize = INIT_SIZE;

    return OK;
}
Status DestroyList(SqList *L)
{
    if(0 == L->listsize)
	return ERROR;
    L->length = 0;
    L->listsize = 0;

    free(L->base);

    return OK;
}
Status ClearList(SqList *L)
{
    if(0 == L->listsize)
	return ERROR;

    L->length = 0;
    return OK;

}
Status ListEmpty(SqList L)
{
    if(L.length)
	return FALSE;
    else
	return TURE;
}
int ListLength(SqList L)

{
    if(0 == L.listsize)
	return ERROR;
    return (L.length);
}
Status GetElem(SqList L,int i,int *e)
{


    if(0 == L.listsize)

	return ERROR;


    if(i>=1 && i<=L.length)
    {
	*e = L.base[i-1];	
	return OK;
    }

    else
	return ERROR;
}
int LocateElem(SqList L,int e,Status (*f)(int a,int b))
{
    if(0 == L.listsize)
	return ERROR;
    int i = 0;
    for(;i<L.length;i++)
	if(f(e,L.base[i]))
	    return (i+1);
    return ERROR;
}
Status PriorElem(SqList L,int cur_e,int *pre_e)
{
    if(0 == L.listsize)
	return ERROR;
    int i = 1;
    for(;i<L.length;i++)
	if(cur_e == L.base[i])
	{
	    *pre_e = L.base[i-1];
	    return OK;
	}
    return ERROR;
}
Status NextElem(SqList L,int cur_e,int *next_e)
{
    if(0 == L.listsize)
	return ERROR;
    int i = 0;
    for(;i<(L.length-1);i++)
	if(cur_e == L.base[i])
	{
	    *next_e = L.base[i+1];
	    return OK;
	}
    return ERROR;
}
Status ListInsert(SqList *L,int i,int e)
{



    if(0 == L->listsize)
	return ERROR;


    if(i>=1 && i<=(L->length+1)) 
    {
	//list full,realloc it
		if(L->listsize == L->length)
		{
			L->base = (int *)realloc(L->base,( L->listsize+INCREMENT));//*sizeof(int));
			L->listsize += INCREMENT;
		}

	//move all elements after i-1 
	int j;
	for(j=L->length;j>=i;j--)
	    L->base[j] = L->base[j-1];

	L->base[i-1] = e;
	L->length++;
	return OK;
    }

    else

	return ERROR;
} 

Status ListDelete(SqList *L,int i,int *e)
{
    if(0 == L->listsize)
	return ERROR;
    if(i>=1 && i<=L->length)
    {
	*e = L->base[i-1];
	int j;
	for(j=L->length-1;j>i;j--)
	    L->base[j-1] = L->base[j];
	L->length--;
    }
    else
	return ERROR;
}

Status ListTraverse(SqList L,void(*f)(int e))
{    
    if(0 == L.listsize)
	return ERROR;
    int i;
    for(i=0;i<L.length;i++)
	f(L.base[i]);
    return OK;
}

Status PrintList(SqList L,char *name)
{
    if(0 == L.listsize)
	return ERROR;

    printf("%s:",name);
    int i;
    for(i=0;i<L.length;i++)
	printf("%d ",L.base[i]);
    printf("\n");
}



